﻿using DataWasher.WebApi.Repositories;
using Microsoft.Azure.Cosmos.Table;
using Report.WebApi.Interfaces;
using Report.WebApi.Models;
using Report.WebApi.Models.ResponseModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ToolManager.Entities;
using ToolManager.IService;

namespace Report.WebApi.Services
{
    public class QuerySPSCService : QueryService, IQuerySPSCService
    {
        private readonly IStorageService _storageService;
        private readonly ISysDomainRepository _repository;
        public QuerySPSCService(IStorageService storageService, ISysDomainRepository repository) : base(repository)
        {
            _storageService = storageService;
            _repository = repository;
        }
        public async Task<SPSCResponse> GetHomePageData(QueryRequestModel request)
        {
            var response = new SPSCResponse();
            var thisData = new List<BusinessDataEntity>();

            try
            {
                //组装查询条件
                var thisYear = await GetMonthsThisYear(request);
                var filter = await ParamBuilder(request, thisYear);
                var query = new TableQuery<BusinessDataEntity>().Where(filter);
                var queryData = await _storageService.GetBusData("Businessdata", query);

                if (_connectionStrings.isDebug == 0)
                {
                    var domainIds = await GetDomainIds(request);
                    queryData = queryData.Where(x => domainIds.Contains(x.DomainId)).ToList();
                }

                if (request.QueryByYear)
                    thisData = queryData.Where(x => x.AddDateYM >= thisYear.QueryBegin && x.AddDateYM <= thisYear.QueryEnd).ToList();

                if (request.QueryByMonth || request.QueryByCustom || request.QueryByQuarter)
                    thisData = queryData.Where(x => x.AddDate >= thisYear.QueryBegin && x.AddDate <= thisYear.QueryEnd).ToList();

                Func<BusinessDataEntity, bool> expression = x => (DateTime.Parse(string.IsNullOrEmpty(x.TaskingDate) ? "0001-01-01" : x.TaskingDate) - DateTime.Parse($"{x.AddDateYear}-{x.AddDateMonth}-{x.AddDateDay}")).Days <= 3;
                response.Count03 = thisData.Where(expression).Count();

                expression = x => (DateTime.Parse(string.IsNullOrEmpty(x.TaskingDate) ? "0001-01-01" : x.TaskingDate) - DateTime.Parse($"{x.AddDateYear}-{x.AddDateMonth}-{x.AddDateDay}")).Days > 3
                && (DateTime.Parse(string.IsNullOrEmpty(x.TaskingDate) ? "0001-01-01" : x.TaskingDate) - DateTime.Parse($"{x.AddDateYear}-{x.AddDateMonth}-{x.AddDateDay}")).Days <= 6;
                response.Count36 = thisData.Where(expression).Count();

                expression = x => (DateTime.Parse(string.IsNullOrEmpty(x.TaskingDate) ? "0001-01-01" : x.TaskingDate) - DateTime.Parse($"{x.AddDateYear}-{x.AddDateMonth}-{x.AddDateDay}")).Days > 6
               && (DateTime.Parse(string.IsNullOrEmpty(x.TaskingDate) ? "0001-01-01" : x.TaskingDate) - DateTime.Parse($"{x.AddDateYear}-{x.AddDateMonth}-{x.AddDateDay}")).Days <= 9;
                response.Count69 = thisData.Where(expression).Count();

                expression = x => (DateTime.Parse(string.IsNullOrEmpty(x.TaskingDate) ? "0001-01-01" : x.TaskingDate) - DateTime.Parse($"{x.AddDateYear}-{x.AddDateMonth}-{x.AddDateDay}")).Days > 9
               && (DateTime.Parse(string.IsNullOrEmpty(x.TaskingDate) ? "0001-01-01" : x.TaskingDate) - DateTime.Parse($"{x.AddDateYear}-{x.AddDateMonth}-{x.AddDateDay}")).Days <= 12;
                response.Count912 = thisData.Where(expression).Count();

                expression = x => (DateTime.Parse(string.IsNullOrEmpty(x.TaskingDate) ? "0001-01-01" : x.TaskingDate) - DateTime.Parse($"{x.AddDateYear}-{x.AddDateMonth}-{x.AddDateDay}")).Days > 12
                && (DateTime.Parse(string.IsNullOrEmpty(x.TaskingDate) ? "0001-01-01" : x.TaskingDate) - DateTime.Parse($"{x.AddDateYear}-{x.AddDateMonth}-{x.AddDateDay}")).Days <= 15;
                response.Count1215 = thisData.Where(expression).Count();

                expression = x => (DateTime.Parse(string.IsNullOrEmpty(x.TaskingDate) ? "0001-01-01" : x.TaskingDate) - DateTime.Parse($"{x.AddDateYear}-{x.AddDateMonth}-{x.AddDateDay}")).Days > 15
               && (DateTime.Parse(string.IsNullOrEmpty(x.TaskingDate) ? "0001-01-01" : x.TaskingDate) - DateTime.Parse($"{x.AddDateYear}-{x.AddDateMonth}-{x.AddDateDay}")).Days <= 18;
                response.Count1518 = thisData.Where(expression).Count();

                expression = x => (DateTime.Parse(string.IsNullOrEmpty(x.TaskingDate) ? "0001-01-01" : x.TaskingDate) - DateTime.Parse($"{x.AddDateYear}-{x.AddDateMonth}-{x.AddDateDay}")).Days > 18
                && (DateTime.Parse(string.IsNullOrEmpty(x.TaskingDate) ? "0001-01-01" : x.TaskingDate) - DateTime.Parse($"{x.AddDateYear}-{x.AddDateMonth}-{x.AddDateDay}")).Days <= 20;
                response.Count1820 = thisData.Where(expression).Count();

                expression = x => (DateTime.Parse(string.IsNullOrEmpty(x.TaskingDate) ? "0001-01-01" : x.TaskingDate) - DateTime.Parse($"{x.AddDateYear}-{x.AddDateMonth}-{x.AddDateDay}")).Days > 20;
                response.Count20 = thisData.Where(expression).Count();

                List<int> daysList = thisData.Select(x => (DateTime.Parse(string.IsNullOrEmpty(x.TaskingDate) ? "0001-01-01" : x.TaskingDate) - DateTime.Parse($"{x.AddDateYear}-{x.AddDateMonth}-{x.AddDateDay}")).Days)
                    .Where(n => n >= 0).ToList<int>();
                daysList.Sort();
                response.Max = daysList.Count() == 0 ? 0 : daysList.Max();
                response.Min = daysList.Count() == 0 ? 0 : daysList.Min();
                response.Avg = thisData.Count() == 0 ? 0 : daysList.Sum() / thisData.Count();
                if (daysList.Count == 0)
                    response.Middle = 0;
                else
                {
                    if (daysList.Count % 2 == 0)
                    {
                        response.Middle = (daysList[daysList.Count / 2 - 1] + daysList[daysList.Count / 2]) / 2;
                    }
                    if (daysList.Count / 2 == 1)
                    {
                        response.Middle = daysList[daysList.Count + 1 / 2];
                    }
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }

            return response;
        }

        public async override Task<string> ParamBuilder(QueryRequestModel request, YearMonthModel filterModel)
        {
            var partitionKey = DateTime.Now.ToString("yyyyMMdd");
            var filterSB = new StringBuilder();
            filterSB.Append($"(PartitionKey eq '{partitionKey}')");
            filterSB.Append(" and ");

            filterSB.Append($"(AddDateYear eq {filterModel.Year})");

            #region 条件组合
            filterSB.Append(" and ");
            filterSB.Append($"(Language eq {request.Language})");

            if (!string.IsNullOrEmpty(request.QueryStore))
            {
                filterSB.Append(" and ");
                filterSB.Append($"(TagName eq '{request.QueryStore}')");
            }

            if (!string.IsNullOrEmpty(request.QueryStatus))
            {
                filterSB.Append(" and ");
                filterSB.Append($"(MntStatus eq '{request.QueryStatus}')");
            }

            if (!string.IsNullOrEmpty(request.QueryPriority))
            {
                filterSB.Append(" and ");
                filterSB.Append($"(Priority eq '{request.QueryPriority}')");
            }
            if (!string.IsNullOrEmpty(request.QueryMntanCategory))
            {
                filterSB.Append(" and ");
                filterSB.Append($"(MntCategory2 eq '{request.QueryMntanCategory}')");
            }
            #endregion
            return filterSB.ToString();
        }

    }
}


